from uplink import Uplink
import os, shutil, zipfile
import settings

class CheckOut():
    def __init__(self,url):
        self.uplink = Uplink(url)

    def getversion(self, url):
        try:
            f = open(url+'version')
            version = f.read()
            return version
        except:
            return -1

    def run(self, path, force = False):
          fulldestination = settings.TRUNK + path
          fullsource = settings.REST_PATH + path
          if not force:
              version = self.getversion(fulldestination)
          else:
              version = -1
          print fullsource + str(version)
          status, response = self.uplink.get(fullsource + str(version))
          if status==200:
              shutil.rmtree(fulldestination)
              os.makedirs(fulldestination)
              print fulldestination+'extras.zip'
              self.uplink.store_file(fulldestination+'extras.zip',response)
              z = zipfile.ZipFile(fulldestination+'extras.zip')
              z.extractall(fulldestination)
              z.close()
              print 'Mapreduce was updated'
              return True
          if status==201:
              print 'Mapreduce wasn\'t changed'
              return True
          return False